package com.comall.dc.banktest.storage;

import com.comall.dc.banktest.domain.exception.AccountNotExistException;
import com.comall.dc.banktest.domain.model.Account;
import com.comall.dc.banktest.domain.repository.AccountRepository;
import com.comall.dc.banktest.infrastructure.dao.service.AccountDAO;
import com.comall.dc.banktest.infrastructure.entity.AccountPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public class AccountStorage implements AccountRepository {

    @Autowired
    private AccountDAO accountService;

    @Override
    public Account load(Integer id) throws AccountNotExistException {
        return new Account(Optional.ofNullable(accountService.getById(id))
                .orElseThrow(AccountNotExistException::new));
    }

    @Override
    public Account save(Account account) {
        AccountPO accountPO = new AccountPO();
        accountPO.setId(account.getId());
        accountPO.setIdCard(account.getIdCard());
        accountPO.setAccountSalt(account.getAccountSalt());
        accountPO.setAccountStatus(account.getAccountStatus().getStatus());
        accountPO.setAccountPassword(account.getAccountPassword());
        accountPO.setBalance(account.getBalance());
        accountPO.setUserAddress(account.getUserAddress());
        accountPO.setUserJob(account.getUserJob());
        accountPO.setUserName(account.getUserName());
        accountPO.setUserPhone(account.getUserPhone());
        if (accountPO.getId() == null){
            accountService.save(accountPO);
        }
        else {
            accountService.updateById(accountPO);
        }

        return new Account(accountPO);
    }
}
